package com.lwlk.zdk.Timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lwlk.zdk.annotation.JwtIgnore;
import com.lwlk.zdk.mapper.T.TDisPlatformMapper;
import com.lwlk.zdk.mapper.pw.pwAssessGradeMapper;
import com.lwlk.zdk.mapper.task.pwTaskPlatformAssessmentStatisticsMapper;
import com.lwlk.zdk.model.task.pwTaskPlatformAssessmentStatistics;
import com.lwlk.zdk.util.HttpClientUtils;
import com.lwlk.zdk.util.PropUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

//平台考核统计
@Component
@EnableScheduling
public class PlatformAssessmentTask {


    private final static String port = PropUtils.getString("ports");
    private final static String Ip = PropUtils.getString("Ip");
    private final static String clientCode = PropUtils.getString("clientCode");

    private static final Logger log = LoggerFactory.getLogger(PlatformAssessmentTask.class);

    @Autowired
    pwAssessGradeMapper pwAssessGradeMapper;
    @Autowired
    pwTaskPlatformAssessmentStatisticsMapper ptpsMapper;
    @Autowired
    TDisPlatformMapper disPlatformMapper;
    @JwtIgnore
    @Scheduled(cron = "0 20 3 * * ?")//每天三点二十分执行
    public void PlatformDate(){

        double netRateNumber=0;//入网率分数
        double onlineRateNumber=0;//上线率分数
        double trackFullRateNumber=0;//轨迹完整率分数
        double passRateNumber=0;//数据合格率分数
        double driftingRateNumber=0;//漂移率分数
        double overspeedCountNumber=0;//平均车辆超速次数分数
        double fatigueDrivingTimeNumber=0;//平均疲劳驾驶时长分数
        double connectRateNumber=0;//平台连通率分数
        double crossRateNumber=0;//跨域数据交换成功率分数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -1);//-1.昨天时间 0.当前时间 1.明天时间 *以此类推
        //String time = sdf.format(c.getTime());
        Map map=new HashMap();
        String time="2020-11-14";
        map.put("date",time);//必传 查询时间yyyy-MM
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/assessment/platform/data";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONArray jsonArray=json.getJSONArray("result");
        if (jsonArray==null){
            //return json;
            log.info(json.toJSONString());
        }
        String assessType="1";
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            String netRate=jsonObject.getString("netRate");//入网率
            String onlineRate=jsonObject.getString("onlineRate");//上线率
            String trackFullRate=jsonObject.getString("trackFullRate");//轨迹完整率
            String passRate=jsonObject.getString("passRate");//数据合格率
            String driftingRate=jsonObject.getString("driftingRate");//漂移率
            String overspeedCount=jsonObject.getString("overspeedCount");//平均车辆超速次数
            String fatigueDrivingTime=jsonObject.getString("fatigueDrivingTime");//平均疲劳驾驶时长
            String connectRate=jsonObject.getString("connectRate");//平台连通率
            String crossRate=jsonObject.getString("crossRate");//跨域数据交换成功率
            String type=jsonObject.getString("type");//考核周期
            String pId=jsonObject.getString("pId");//平台id
            String TheInspectionTime=jsonObject.getString("createTime");//考核时间

            int count=pwAssessGradeMapper.selectByType(type,assessType);
            if (count==0){
                log.info("列表中有未创建的考核周期或考核类型的参数,请创建对应的考核评分规则");
                continue;
            }

            //获取平台名称
            String platformName=disPlatformMapper.selectBypId(Integer.parseInt(pId));
            String platformCode=disPlatformMapper.selectAccessCode(Integer.parseInt(pId));//获取地区码
            jsonObject.put("platformName",platformName);

            //获取考核周期
            String assessPeriod =type.equals("0") ? "日考核" : (type.equals("1") ? "周考核" : type.equals("2") ? "月考核" : type.equals("3") ? "年考核" : null);
            jsonObject.put("assessPeriod",assessPeriod);

            //获取行政区划地

                /*wdHfArea wdHfArea=wdHfAreaMapper.selectByPrimaryKey(admdivcode);
                jsonObject.put("areaCode",wdHfArea.getName());*/
            NumberFormat nf = java.text.NumberFormat.getPercentInstance();
            nf.setMinimumFractionDigits(0);// 小数点后保留0位
            List<Map> assessGradeIdList=pwAssessGradeMapper.selectAssessGradeId(pId,assessType,type);//查询出此考核评分中有该企业的考核评分
            if (assessGradeIdList.size()==0){//当此企业没有在考核评分表中,描述中填写此企业未能参与考核评分
                String describe=platformName+"未能参与考核评分";
                pwTaskPlatformAssessmentStatistics pwTaskPlatformAssessmentStatistics=new pwTaskPlatformAssessmentStatistics();
                pwTaskPlatformAssessmentStatistics.setpId(Integer.parseInt(pId));
                pwTaskPlatformAssessmentStatistics.setPlatformName(platformName);
                pwTaskPlatformAssessmentStatistics.setDescribe(describe);
                pwTaskPlatformAssessmentStatistics.setType(Integer.parseInt(type));
                pwTaskPlatformAssessmentStatistics.setTypeName(assessPeriod);
                pwTaskPlatformAssessmentStatistics.setTheInspectionTime(TheInspectionTime);
                pwTaskPlatformAssessmentStatistics.setStatus(2);
                pwTaskPlatformAssessmentStatistics.setRegionCode(platformCode);
                int regionNull=ptpsMapper.insertSelective(pwTaskPlatformAssessmentStatistics);
                continue;
            }
            for (int j = 0; j < assessGradeIdList.size(); j++) {
                //计算入网率得分
                String indexName="0";//车辆入网率
                List<Map<String,Object>> assessGrade=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexName);//入网率参数
                Double netRateNum=Double.valueOf(netRate);//将入网率转成double
                String RuWangLv = nf.format(netRateNum);//入网率转成百分数
                if (assessGrade.size()>0){
                    if (assessGrade.size()>0){
                        String s=RuWangLv.replace("%","");
                        if (Integer.parseInt(s)<Integer.parseInt(String.valueOf(assessGrade.get(0).get("lowestMarkRatio")))){//如果入网率低于指标,不得分
                            netRateNumber=0;
                        }else {
                            netRateNumber=netRateNum*Integer.parseInt(String.valueOf(assessGrade.get(0).get("score")));//入网率得分
                            BigDecimal bn = new BigDecimal(netRateNumber);
                            netRateNumber = bn.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }
                    }else {
                        netRateNumber=0;
                    }
                }



                //计算上线率分数
                Double onlineRateNum=Double.valueOf(onlineRate);//将上线率转成double
                String indexNameOnline="1";//车辆上线率
                String OnlineRate=nf.format(onlineRateNum);//上线率转成百分数
                List<Map<String,Object>> assessGradeOnline=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameOnline);//上线率参数
                if (assessGradeOnline.size()>0){
                    if (assessGradeOnline.size()>0){
                        onlineRateNumber=onlineRateNum*Integer.parseInt(String.valueOf(assessGradeOnline.get(0).get("score")));//上线率得分
                        BigDecimal bn = new BigDecimal(onlineRateNumber);
                        onlineRateNumber = bn.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    }else {
                        onlineRateNumber=0;
                    }
                }



                //计算轨迹完整率分数
                String indexNameTrack="2";//轨迹完整率
                List<Map<String,Object>> assessGradeTrack=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameTrack);//轨迹完整率参数
                Double trackFullRateNum=Double.valueOf(trackFullRate);//将轨迹完整率转成double
                String TrajectoryIntegrityRate = nf.format(trackFullRateNum);//轨迹完整率转成百分数
                String track=TrajectoryIntegrityRate.replace("%","");
                if (assessGradeTrack.size()>0){
                    if (assessGradeTrack.size()>0){
                        if (Integer.parseInt(track)<Integer.parseInt(String.valueOf(assessGradeTrack.get(0).get("lowestMarkRatio")))){//如果轨迹完整率低于指标,不得分
                            trackFullRateNumber=0;
                        }else {
                            trackFullRateNumber=trackFullRateNum*Integer.parseInt(String.valueOf(assessGradeTrack.get(0).get("score")));//轨迹完整率得分
                            BigDecimal trackBig = new BigDecimal(trackFullRateNumber);
                            trackFullRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }
                    }else {
                        trackFullRateNumber=0;
                    }
                }



                //计算数据合格率分数
                String indexNamePass="3";//数据合格率
                List<Map<String,Object>> assessGradePass=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNamePass);//轨迹完整率参数
                Double passRateNum=Double.valueOf(passRate);//将数据合格率转成double
                String DataPassRate = nf.format(passRateNum);//数据合格率转成百分数
                String passRateInt=DataPassRate.replace("%","");
                if (assessGradePass.size()>0){
                    if (Integer.parseInt(passRateInt)<Integer.parseInt(String.valueOf(assessGradePass.get(0).get("lowestMarkRatio")))){//如果数据合格率低于指标,不得分
                        passRateNumber=0;
                    }else {
                        passRateNumber=passRateNum*Integer.parseInt(String.valueOf(assessGradePass.get(0).get("score")));//数据合格率得分
                        BigDecimal trackBig = new BigDecimal(passRateNumber);
                        passRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    }
                }else {
                    passRateNumber=0;
                }


                //计算漂移率分数
                String indexNameDrifting="4";//漂移率
                List<Map<String,Object>> assessGradeDrifting=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameDrifting);//轨迹完整率参数
                Double driftingNum=Double.valueOf(driftingRate);//将漂移率转成double
                String driftRate = nf.format(driftingNum);//漂移率转成百分数
                String driftingInt=driftRate.replace("%","");
                if (assessGradeDrifting.size()>0){
                    if (assessGradeDrifting.size()>0){
                        if (Integer.parseInt(driftingInt)<Integer.parseInt(String.valueOf(assessGradeDrifting.get(0).get("lowestMarkRatio")))){//如果数据合格率低于指标,不得分
                            driftingRateNumber=0;
                        }else {
                            driftingRateNumber=driftingNum*Integer.parseInt(String.valueOf(assessGradeDrifting.get(0).get("score")));//数据合格率得分
                            BigDecimal trackBig = new BigDecimal(driftingRateNumber);
                            driftingRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }
                    }else {
                        driftingRateNumber=0;
                    }
                }
                //计算平均车辆超速次数分数
                String indexNameOverspeedCount="5";//平均车辆超速次数
                List<Map<String,Object>> assessGradeOverspeedCount=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameOverspeedCount);//平均车辆超速次数参数
                Double overspeedCountNum=Double.valueOf(overspeedCount);//将平均车辆超速次数转成double
                String overspeed = nf.format(overspeedCountNum);//平均车辆超速次数转成百分数
                String overspeedInt=overspeed.replace("%","");
                if (assessGradeOverspeedCount.size()>0){
                    if (assessGradeOverspeedCount.size()>0){
                        if (Integer.parseInt(overspeedInt)<Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))){//如果平均车辆超速次数低于指标 算法:10+(指标 - 平均车速次数)/指标 * 10
                            overspeedCountNumber=10+(Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))-Integer.parseInt(overspeedInt))/Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))*10;
                        }else if (Integer.parseInt(overspeedInt)>Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio"))) && Integer.parseInt(overspeedInt)<Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))*2){//如果平均车辆超速次数高于指标并小于指标的2倍
                            overspeedCountNumber=(Integer.parseInt(String.valueOf(assessGradeDrifting.get(0).get("score")))*2-overspeedCountNum)/Integer.parseInt(String.valueOf(assessGradeDrifting.get(0).get("score")))*10;//平均车辆超速次数得分
                            BigDecimal trackBig = new BigDecimal(overspeedCountNumber);
                            overspeedCountNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//四舍五入
                        }else if (Integer.parseInt(overspeedInt)>Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))*2){//如果平均车辆超速次数大于指标的2倍,不得分
                            overspeedCountNumber=0;
                        }
                    }else {
                        overspeedCountNumber=0;
                    }
                }
                //计算平均疲劳驾驶时长分数
                String indexNameFatigueDriving="6";//平均疲劳驾驶时长
                List<Map<String,Object>> assessGradeFatigueDriving=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameFatigueDriving);//平均疲劳驾驶时长参数
                Long ff=Long.valueOf(fatigueDrivingTime);//将平均疲劳驾驶时长转成Long
                String FatigueDrivingTime=String.valueOf(ff);//平均疲劳驾驶时长
                if (assessGradeFatigueDriving.size()>0){
                    if (assessGradeFatigueDriving.size()>0){
                        if (ff.longValue()<Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("lowestMarkRatio"))).longValue()){//如果平均疲劳驾驶时长低于指标,算法:10+(指标 - 平均疲劳驾驶时长)/指标 * 10
                            fatigueDrivingTimeNumber=10+(Integer.parseInt(String.valueOf(assessGradeFatigueDriving.get(0).get("score")))-Integer.parseInt(overspeedInt))/Integer.parseInt(String.valueOf(assessGradeFatigueDriving.get(0).get("score")))*10;
                            BigDecimal trackBig = new BigDecimal(fatigueDrivingTimeNumber);
                            fatigueDrivingTimeNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }else if (ff.longValue()>Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("lowestMarkRatio")))&&ff.longValue()<Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("lowestMarkRatio")))*2){
                            fatigueDrivingTimeNumber=(Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("score")))*2-ff)/Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("score")))*10;//平均疲劳驾驶时长得分
                            BigDecimal trackBig = new BigDecimal(fatigueDrivingTimeNumber);
                            fatigueDrivingTimeNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }else if (ff.longValue()>Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("lowestMarkRatio")))*2){//如果平均疲劳驾驶时长大于指标的2倍,不得分
                            fatigueDrivingTimeNumber=0;
                        }
                    }else {
                        fatigueDrivingTimeNumber=0;
                    }
                }
                //计算平台连通率分数
                String indexNameConnect="7";//平台连通率
                List<Map<String,Object>> assessGradeConnect=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameConnect);//平台连通率参数
                Double connectRateNum=Double.valueOf(connectRate);//将平台连通率转成double
                String connect = nf.format(connectRateNum);//平台连通率转成百分数
                if (assessGradeConnect.size()>0){
                    if (assessGradeConnect.size()>0){
                        String connectInt=connect.replace("%","");
                        if (Integer.parseInt(connectInt)>Integer.parseInt(String.valueOf(assessGradeConnect.get(0).get("lowestMarkRatio")))){
                            connectRateNumber=connectRateNum*Integer.parseInt(String.valueOf(assessGradeConnect.get(0).get("score")));
                            BigDecimal trackBig = new BigDecimal(connectRateNumber);
                            connectRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }else {
                            connectRateNumber=0;
                        }
                    }else {
                        connectRateNumber=0;
                    }
                }
                //计算跨域数据交换成功率分数
                String indexNameCross="8";//跨域数据转发
                List<Map<String,Object>> assessGradeCross=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameCross);//跨域数据交换成功率参数
                Double crossRateNum=Double.valueOf(crossRate);//将跨域数据交换成功率转成double
                String CrossDomainData = nf.format(crossRateNum);//跨域数据交换成功率转成百分数
                if (assessGradeCross.size()>0){
                    if (assessGradeCross.size()>0){
                        String crossInt=CrossDomainData.replace("%","");
                        if (Integer.parseInt(crossInt)>Integer.parseInt(String.valueOf(assessGradeCross.get(0).get("lowestMarkRatio")))){
                            crossRateNumber=crossRateNum*Integer.parseInt(String.valueOf(assessGradeCross.get(0).get("score")));
                            BigDecimal trackBig = new BigDecimal(crossRateNumber);
                            crossRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }else {

                        }
                    }else {
                        crossRateNumber=0;
                    }
                }
                double GrossScore=netRateNumber+onlineRateNumber+trackFullRateNumber+passRateNumber+driftingRateNumber+overspeedCountNumber+fatigueDrivingTimeNumber+connectRateNumber+crossRateNumber;
                pwTaskPlatformAssessmentStatistics ptps=new pwTaskPlatformAssessmentStatistics();
                ptps.setpId(Integer.parseInt(pId));
                ptps.setAssessGradeId(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))));
                ptps.setPlatformName(platformName);
                ptps.setGrossScore(GrossScore);
                ptps.setNetRateNumber(netRateNumber);
                ptps.setOnlineRateNumber(onlineRateNumber);
                ptps.setTrackFullRateNumber(trackFullRateNumber);
                ptps.setPassRateNumber(passRateNumber);
                ptps.setDriftingRateNumber(driftingRateNumber);
                ptps.setOverspeedCountNumber(overspeedCountNumber);
                ptps.setFatigueDrivingTimeNumber(fatigueDrivingTimeNumber);
                ptps.setConnectRateNumber(connectRateNumber);
                ptps.setCrossRateNumber(crossRateNumber);
                ptps.setType(Integer.parseInt(type));
                ptps.setTypeName(assessPeriod);
                ptps.setDescribe(platformName+"成功参与考核评分");
                ptps.setTheInspectionTime(TheInspectionTime);
                ptps.setRuWangLv(RuWangLv);
                ptps.setOnlineRate(OnlineRate);
                ptps.setTrajectoryIntegrityRate(TrajectoryIntegrityRate);
                ptps.setDataPassRate(DataPassRate);
                ptps.setDriftRate(driftRate);
                ptps.setOversPeed(overspeedInt);
                ptps.setFatigueDrivingTime(FatigueDrivingTime);
                ptps.setConnect(connect);
                ptps.setCrossDomainData(CrossDomainData);
                ptps.setStatus(1);
                ptps.setRegionCode(platformCode);
                int ptes=ptpsMapper.insertSelective(ptps);
                jsonObject.put("GrossScore",GrossScore);
            }
            for (int j = 0; j < assessGradeIdList.size(); j++) {
                Integer id =Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id")));
                List<Map<String,Object>>cityAndCountyList=ptpsMapper.selectStatus(id,TheInspectionTime,assessPeriod);//根据考核方案考核时间考核周期名称
                for (int k = 0; k < cityAndCountyList.size(); k++) {
                    int rank=k+1;
                    int id1= Integer.parseInt(String.valueOf(cityAndCountyList.get(k).get("id")));
                    int sum=ptpsMapper.updateRanking(id1,rank);
                }
            }
        }
        //return json;
    }
}
